package com.tasly.attendance.domain.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import com.tasly.attendance.domain.AttendanceFileParse;
import com.tasly.attendance.entity.AttendanceRecordEntity;
import com.tasly.attendance.util.AttendanceUtils;

public class AttendanceFileParseImpl implements AttendanceFileParse {
    
    private Map<String, List<AttendanceRecordEntity>> userRecordsMap = new HashMap<String, List<AttendanceRecordEntity>>();
    //there are only 7 valid column in txt file(name is empty in txt file)
    //use  to put all colunm items
    private List<String> tmpColumnList = new ArrayList<String>();
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    
    private static final AttendanceFileParse parser = new AttendanceFileParseImpl();

    private AttendanceFileParseImpl() {
    }
           
    public static AttendanceFileParse getInstance() {
        return parser;
    }

    @Override
    public void parseLine(String line) {
        String userId = null;
        Date userRecordTime = null;
        List<AttendanceRecordEntity> userRecordTimeSet = null;
        
        //clear tmp list before start parse
        tmpColumnList.clear();
        
        if (AttendanceUtils.validateIncomingLine(line)) {
            //replace all '\t' to ' ' in the txt line
            line = line.replaceAll("\t", " ");
            //put column items into temp list
            StringTokenizer st = new StringTokenizer(line," ");
            while (st.hasMoreTokens()) {
                tmpColumnList.add(st.nextToken());
            }
            //get the used items
            userId = tmpColumnList.get(2);
            //check if user record exist in map
            userRecordTimeSet = userRecordsMap.get(userId)==null? new ArrayList<AttendanceRecordEntity>():userRecordsMap.get(userId);
            try {
              //format working time and convert from String to Date
                userRecordTime = dateFormat.parse(tmpColumnList.get(5)+" "+tmpColumnList.get(6));
            } catch (ParseException e) {
                System.out.println("Exception occurred when parse time from string to date!!");
            }
            //store attendance entity into Set
            AttendanceRecordEntity record = new AttendanceRecordEntity();
            record.setUserId(userId);
            record.setWorkingTime(userRecordTime);
            userRecordTimeSet.add(record);
            //store used data in map, use userId as key
            userRecordsMap.put(userId, userRecordTimeSet);
        }
    }
    
    public Map<String, List<AttendanceRecordEntity>> getAttendanceRecordsMap() {
        return this.userRecordsMap;
    }
    
}
